package cn.jobstart.common;


import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.Writer;
import com.google.zxing.WriterException;
import com.google.zxing.client.j2se.MatrixToImageWriter;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.oned.Code128Writer;

import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.util.HashMap;
import java.util.Map;


/**
 * @author sunke
 * @Date 2021/4/8 23:13
 * @description
 */

public class CodeBar128Util implements Writer {


    private static String format = "png";//生成条形码图片类型

    public static void main(String[] args) throws Exception {
        getCodeBar("AMB02-0001-OCKSDJ-02", 335, 40);
    }


    /**
     * 生成条码方法
     *
     * @param content
     * @param width
     * @param height
     * @return
     * @throws Exception
     */
    public static BufferedImage getCodeBar(String content, int width, int height) throws Exception {
        HashMap<EncodeHintType, Comparable> hints = new HashMap<EncodeHintType, Comparable>();
        hints.put(EncodeHintType.CHARACTER_SET, "utf-8");
        hints.put(EncodeHintType.MARGIN, 3);

        BitMatrix encode = new CodeBar128Util().encode(content, BarcodeFormat.CODE_128, width, height, hints);
        return MatrixToImageWriter.toBufferedImage(encode);
       // ImageIO.write(bufferedImage, "png", new FileOutputStream(new File("/Users/sunke/Desktop/aa/bb.png")));
    }

    public static byte[] getCodeBar(String content) {
        HashMap<EncodeHintType, Comparable> hints = new HashMap<EncodeHintType, Comparable>();
        hints.put(EncodeHintType.CHARACTER_SET, "utf-8");
        hints.put(EncodeHintType.MARGIN, 3);

        ByteArrayOutputStream ot = new ByteArrayOutputStream();
        try {
            //设置宽高比例，自己调，这里主要是固定了宽度，高度不一致
            int width = new Code128Writer().encode(content).length;
            int height = width / 2;
            BitMatrix bm = new CodeBar128Util().encode(content, BarcodeFormat.CODE_128, width, height, hints);
            MatrixToImageWriter.writeToStream(bm, format, ot);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return ot.toByteArray();
    }

    @Override
    public final BitMatrix encode(String contents, BarcodeFormat format, int width, int height)
            throws WriterException {
        return encode(contents, format, width, height, null);
    }

    /**
     * Encode the contents following specified format.
     * {@code width} and {@code height} are required size. This method may return bigger size
     * {@code BitMatrix} when specified size is too small. The user can set both {@code width} and
     * {@code height} to zero to get minimum size barcode. If negative value is set to {@code width}
     * or {@code height}, {@code IllegalArgumentException} is thrown.
     */
    @Override
    public BitMatrix encode(String contents,
                            BarcodeFormat format,
                            int width,
                            int height,
                            Map<EncodeHintType, ?> hints) throws WriterException {
        if (contents.isEmpty()) {
            throw new IllegalArgumentException("Found empty contents");
        }

        if (width < 0 || height < 0) {
            throw new IllegalArgumentException("Negative size is not allowed. Input: "
                    + width + 'x' + height);
        }

        int sidesMargin = 2;
        if (hints != null && hints.containsKey(EncodeHintType.MARGIN)) {
            sidesMargin = Integer.parseInt(hints.get(EncodeHintType.MARGIN).toString());
        }

        boolean[] code = new Code128Writer().encode(contents);
        return renderResult(code, width, height, sidesMargin);
    }

    /**
     * @return a byte array of horizontal pixels (0 = white, 1 = black)
     */
    private static BitMatrix renderResult(boolean[] code, int width, int height, int sidesMargin) {
        int inputWidth = code.length;
        int fullWidth = inputWidth;

        int outputWidth=0;
        if (width % inputWidth == 0) {
            outputWidth = width;
        }
        outputWidth = width > inputWidth ? width / inputWidth * inputWidth : (width / inputWidth + 1) * inputWidth;
        int outputHeight = Math.max(1, height);

        int multiple = outputWidth / fullWidth;
        int leftPadding = sidesMargin;

        BitMatrix output = new BitMatrix(width, outputHeight);
        for (int inputX = 0, outputX = leftPadding; inputX < inputWidth; inputX++, outputX += multiple) {
            if (code[inputX]) {
                output.setRegion(outputX, 0, multiple, outputHeight);
            }
        }
        return output;

    }


}
